<template>
  <div class="form">
    <LoginFormTitle v-show="getShow" class="enter-x" />
    <Form
      class="p-4 enter-x login-form"
      :model="formData"
      :rules="getFormRules"
      ref="formRef"
      v-show="getShow"
      @keypress.enter="handleLogin"
    >
      <FormItem name="username" class="enter-x">
        <Input
          size="large"
          v-model:value="formData.username"
          :placeholder="t('sys.login.userName')"
          class="fix-auto-fill"
        >
          <template #prefix>
            <user-outlined type="user" />
          </template>
        </Input>
      </FormItem>
      <FormItem name="password" class="enter-x">
        <InputPassword
          size="large"
          visibilityToggle
          v-model:value="formData.password"
          :placeholder="t('sys.login.password')"
        >
          <template #prefix>
            <LockOutlined></LockOutlined>
          </template>
        </InputPassword>
      </FormItem>

      <FormItem name="code" class="enter-x" v-if="false">
        <ARow align="top">
          <ACol :span="17">
            <Input
              size="large"
              v-model:value="formData.code"
              :placeholder="t('sys.login.code')"
              class="fix-auto-fill"
            />
          </ACol>
          <ACol :span="6" :offset="1">
            <img :src="imgSrc" @click="getCode" />
          </ACol>
        </ARow>
      </FormItem>

      <FormItem class="enter-x">
        <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
          {{ t('sys.login.loginButton') }}
        </Button>
      </FormItem>

      <ARow class="enter-x">
        <ACol :span="12">
          <FormItem>
            <Checkbox v-model:checked="rememberMe" size="small">
              {{ t('sys.login.rememberMe') }}
            </Checkbox>
          </FormItem>
        </ACol>
        <ACol :span="12">
          <FormItem :style="{ 'text-align': 'right' }">
            <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
              {{ t('sys.login.forgetPassword') }}
            </Button>
          </FormItem>
        </ACol>
      </ARow>
    </Form>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, computed, onMounted } from 'vue';
  import { Checkbox, Form, Input, Row, Col, Button } from 'ant-design-vue';
  import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
  import LoginFormTitle from './LoginFormTitle.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { captchaApi } from '/@/api/user/login';

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { t } = useI18n();
  const { notification, createErrorModal } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();
  const { setLoginState, getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();
  const formRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);
  const imgSrc = ref();
  const formData = reactive({
    username: '',
    password: '',
    code: '',
    uuid: '',
    id: '',
  });

  const { validForm } = useFormValid(formRef);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);

  // 获取图片验证码
  const getCode = async () => {
    const res = await captchaApi();
    imgSrc.value = res.data.img;
    formData.uuid = res.data.uuid;
  };

  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;
      const userInfo = await userStore.login({
        password: data.password,
        username: data.username,
        code: data.code,
        uuid: formData.uuid,
      });

      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realName}`,
          duration: 3,
        });
      }
    } catch (error) {
      console.error(error);
      createErrorModal({
        title: t('sys.api.errorTip'),
        content: error || t('sys.api.networkExceptionMsg'),
        getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
      });
      // getCode();
    } finally {
      loading.value = false;
    }
  }

  onMounted(() => {
    // getCode();
  });
</script>

<style lang="less" scoped>
  .form {
    .login-form {
      margin-top: 50px;
    }
  }
</style>
